package tenant

import (
	"context"
	"encoding/json"

	v1 "gitee.com/liangziyisheng/caas-platform-mc/api/tenant/v1"
	"gitee.com/liangziyisheng/caas-platform-mc/internal/consts"
	"gitee.com/liangziyisheng/caas-platform-mc/internal/model/entity"
	"gitee.com/liangziyisheng/caas-platform-mc/internal/service"
	"gitee.com/liangziyisheng/caas-platform-mc/utility/cache"
	"gitee.com/liangziyisheng/caas-platform-mc/utility/utils"

	"github.com/gogf/gf/v2/errors/gerror"
)

func (c *ControllerV1) Add(ctx context.Context, req *v1.AddReq) (res *v1.AddRes, err error) {

	// 加强数据校验
	cc, _ := cache.NewCache()
	cache.InitCache(ctx, consts.InitialCacheKeys.RegionsKey, false)
	val, err := cc.Get(ctx, consts.InitialCacheKeys.RegionsKey)
	if err != nil {
		return nil, gerror.WrapCode(consts.GetCacheFailed, err)
	}
	regionStr, ok := val.Val().(string)
	if !ok {
		return nil, gerror.WrapCode(consts.ParseCacheFailed, gerror.New("行政缓存存储出错"))
	}
	regionMap := make(map[string]entity.Region, 0)
	json.Unmarshal([]byte(regionStr), &regionMap)

	if len(req.CountryCode) > 0 {
		if _, ok := regionMap[req.CountryCode]; !ok {
			return nil, gerror.WrapCode(consts.RegionCodeNotExist, gerror.New(req.CountryCode))
		}
	}
	if len(req.ProvinceCode) > 0 {
		if _, ok := regionMap[req.ProvinceCode]; !ok {
			return nil, gerror.WrapCode(consts.RegionCodeNotExist, gerror.New(req.ProvinceCode))
		}
	}
	if len(req.CityCode) > 0 {
		if _, ok := regionMap[req.CityCode]; !ok {
			return nil, gerror.WrapCode(consts.RegionCodeNotExist, nil, req.CityCode)
		}
	}
	if len(req.CountyCode) > 0 {
		if _, ok := regionMap[req.CountyCode]; !ok {
			return nil, gerror.WrapCode(consts.RegionCodeNotExist, nil, req.CountyCode)
		}
	}
	in := &v1.AddInput{}
	utils.CopyStruc(*req, in)
	in.Status = true
	res = &v1.AddRes{}
	out, err := service.Tenant().Add(ctx, in)
	if err != nil {
		return nil, err
	}
	res.Id = out.Id
	return res, nil
}
